package com.cfc.stage1;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 两数之和
 *   https://leetcode.cn/problems/two-sum/description/
 * @author: yangxuan10
 * @create: 2024-04-02 14:53
 **/
public class TwoSum {


    @Test
    public void test() {

    }

    /**
     * 这个也是官方题解啦：我觉得主要考察的是，如果已经出现过的数字，我们存一下，用空间换时间
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>(16);
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            } else {
                map.put(nums[i], i);
            }
        }
        return null;
    }

    /**
     *  用了两层for循环，效率上要差一点啊
     */
    public int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    int[] arr = new int[2];
                    arr[0] = i;
                    arr[1] = j;
                    return arr;
                }
            }
        }
        return null;
    }

}